package lucene;

import lucene.dao.IndexingGoodsDao;
import lucene.entity.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.shiro.util.CollectionUtils;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.LBHttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.vacoor.nothing.common.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import static org.vacoor.nothing.security.lucene.SolrGoodsSearchServiceImpl.*;

public class SolrTestDataBuilder {
    public static final String MODEL_FIELD = "model";
    public static final String MODEL_VAL_PREFIX = "model_";

    public static void main(String[] args) throws SolrServerException, IOException {
        System.out.println("---------");
        String[] urls = {
                "http://127.0.0.1:8888/noahs",          // 本地测试
                "http://121.41.31.94/solr/noahs",        // 阿里云
                "http://192.168.1.123:8080/solr/noahs" // 123
        };
        /*
        urls = new String[] {
                "http://127.0.0.1:8888/jiusu",          // 本地测试
                // "http://192.168.1.123:8080/solr/jiusu", // 废弃
                "http://anyforweb.com:8080/solr/jiusu"  // 外网
        };
        */
        // new ConcurrentUpdateSolrServer()
        // new CloudSolrServer()

        SolrServer solrServer = new LBHttpSolrServer(null, new String[]{urls[1]}); // 只能做负载均衡查询, 更新,删除没法全部都删除

        solrServer.deleteByQuery("*:*");
//        buildTestDataFromDB(solrServer, false);
//        buildTestDataFromDB(solrServer, true);
        solrServer.commit();
    }

    public static void buildTestDataFromDB(SolrServer solrServer, boolean multiCat) throws IOException, SolrServerException {
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = sf.openSession();

        IndexingGoodsDao mapper = session.getMapper(IndexingGoodsDao.class);
        List<IndexedGoods> all = multiCat ? mapper.findManyMultiCatGoods(new HashMap<String, Object>()) : mapper.findMany(new HashMap<String, Object>());
        for (IndexedGoods goods : all) {
            SolrInputDocument doc = new SolrInputDocument();
            doc.addField("id", goods.getId());
            String title = goods.getTitle();
            title = StringUtils.hasText(title) ? title : goods.getProductTitle();
            doc.addField("title", title);

            // 添加价格
            doc.addField(PRICE_FIELD, goods.getPrice());
            doc.addField("marketPrice", goods.getMarketPrice());
            // 添加销量
            doc.addField("sales", goods.getSales());
            // 添加所有分类
            List<Cat> cats = goods.getCats();
            if (null != cats) {
                for (Cat cat : cats) {
                    for (; null != cat; cat = cat.getParent()) {
                        String catId = cat.getId();
                        String catName = cat.getName();
                        Cat p = cat.getParent();
                        String value = null == p ? catName : catName + MIX_VAL_DELIMITER + p.getId() + MIX_VAL_DELIMITER + p.getName();

                        doc.addField(CAT_FIELD, catId);
                        doc.addField(CAT_VAL_PREFIX + catId, value);
                    }
                }
            }

            // 添加品牌
            doc.addField(BRAND_FIELD, goods.getBrandId());
            doc.addField(BRAND_VAL_FIELD, goods.getBrandName());

            // 添加属性到索引
            List<PropVal> values = goods.getPropVals();
            if (!CollectionUtils.isEmpty(values)) {
                for (PropVal value : values) {
                    Prop prop = value.getProp();
                    if (null == prop) {
                        continue;
                    }

                    String propId = prop.getId();
                    String propName = prop.getName();
                    String valueId = value.getId();
                    String firstValue = value.getFirstValue();
                    String secondValue = value.getSecondValue();

                    firstValue += StringUtils.hasText(secondValue) ? secondValue : "";
                    doc.addField(DYN_PROPS_FIELD, propId);
                    doc.addField(DYN_PROP_PREFIX + propId, valueId);
                    doc.addField(DYN_PROP_VAL_PREFIX + valueId, propName + MIX_VAL_DELIMITER + firstValue);
                }
            }

            doc.addField("pool", goods.getPoolId());
            doc.addField("putawayDate", goods.getPutawayDate());
            List<String> images = goods.getImages();
            if (0 < images.size()) {
                doc.addField("image", images.get(0));
            }

            List<CarModel> models = goods.getModels();
            if (null != models) {
                // 为了去重
                for (CarModel model : models) {
                    CarSeries series = null == model ? null : model.getCarSeries();
                    CarPlace place = null == series ? null : series.getCarPlace();
                    CarBrand brand = null == place ? null : place.getCarBrand();

                    if (null == model || null == series || null == place || null == brand) {
                        continue;
                    }
                    // 车型品牌
                    String bid = brand.getId();
                    String bname = brand.getName();
                    add(doc, MODEL_FIELD, bid);
                    add(doc, MODEL_VAL_PREFIX + bid, bname);

                    // 产地
                    String pid = place.getId();
                    String pname = bname + " " + place.getName();
                    add(doc, MODEL_FIELD, pid);
                    add(doc, MODEL_VAL_PREFIX + pid, pname);

                    // 车系
                    String sid = series.getId();
                    String sname = pname + " " + series.getName();
                    add(doc, MODEL_FIELD, sid);
                    add(doc, MODEL_VAL_PREFIX + sid, sname);

                    // 排量
                    String powerName = model.getPower();
                    String powerId = CarModel.encodePower(sid, powerName);
                    powerName = sname + " " + powerName;
                    add(doc, MODEL_FIELD, powerId);
                    add(doc, MODEL_VAL_PREFIX + powerId, powerName);

                    // 车型
                    add(doc, MODEL_FIELD, model.getId());
                    add(doc, MODEL_VAL_PREFIX + model.getId(), model.getName());
                }
            }
            solrServer.add(doc);
        }
        solrServer.commit();
    }

    protected static void add(SolrInputDocument doc, String field, String value) {
        Collection<Object> values = doc.getFieldValues(field);
        if (null == values || !values.contains(value)) {
            doc.addField(field, value);
        }
    }
}
